<template>
  <div class="companyadmin">
    <!-- 左侧管理 -->
    <div class="left">
      <div class="company-info" v-if="companyData">
        <div class="company-info-content">
          <div class="button-group">
            <template v-if="isRoot">
              <el-button 
                type="text" 
                class="back-button"
                @click="goBackToSystemAdmin"
              >
                < 返回管理页面
              </el-button>
            </template>
            <template v-else>
              <div style="width: 120px; height: 35px;"></div>
            </template>
          </div>
          <div class="company-middle-info">
        <div class="company-name">{{ companyData.name  || ''}}</div>
        <div class="count-info">
          <span>成员总数 {{ companyData.member_num || 0}}</span>
          <span>服务器总数 {{ companyData.system_num || 0 }}</span>
        </div>
      </div>
          <el-button type="text" class="forward-button" @click="handleToolClick('home')"> 查看服务器详情 ></el-button>
        </div>
      </div>
      <div class="main-content">
        <div class="top">
          <div class="button-group">
            <el-button class="button" @click="openAddMemberDialog">+</el-button>
            <el-button class="button" @click="openDeleteSelectedDialog"> -</el-button>
          </div>
          <div class="search-group">
            <el-input v-model="searchQuery" placeholder="请输入搜索内容" class="s-input" :prefix-icon="Search" style="width:400px;height: 35px;"/>
            <el-icon
              style="width: 2rem; height: 2rem; margin-left: 0.5rem; background-color: #ffffff; border-radius: 50%;">
              <Search style="font-size: 1.2rem; color: #000000;" />
            </el-icon>
          </div>
        </div>
        <div class="member-list" style="height: calc(100vh - 320px); overflow-y: auto;">
          <!-- 表头 -->
          <div class="member-header">
            <div class="header-item select-header" style="height: 45px;">
              <el-checkbox v-model="isAllSelected" @change="handleSelectAll" style="color: white;font-weight: bold;">全选</el-checkbox>
            </div>
            <div class="header-item name-header">成员姓名</div>
            <div class="header-item email-header">成员邮箱</div>
            <div class="header-item action-header">操作</div>
          </div>
          <!-- 成员数据 -->
          <div class="member-row" v-for="(member, index) in members" :key="index">
            <div class="member-item select-item">
              <el-checkbox v-model="member.isSelected" @change="checkAllSelected"></el-checkbox>
            </div>
            <div class="member-item name-item">{{ member.username }}</div>
            <div class="member-item email-item">{{ member.email }}</div>
            <button class="deletebutton" 
              :disabled="isCurrentUser(member.username)"
              @click="openDeleteMemberDialog(member)"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加成员弹窗 -->
    <div v-if="showAddMemberDialog" class="addbox">
      <div class="box-title">添加成员</div>
      <div class="divider"></div>
      <div class="input-title">成员姓名</div>
      <div class="input-wrapper">
        <span class="input-icon1">
          <el-icon><UserFilled /></el-icon>
        </span>
        <input type="text" v-model="username" placeholder="请输入成员姓名" class="bar">
      </div>
      <div class="input-title">成员邮箱</div>
      <div class="input-wrapper">
        <span class="input-icon2">
          <el-icon><Comment /></el-icon>
        </span>
        <input type="passwordType" v-model="email" placeholder="请输入成员邮箱" class="bar2">
      </div>
      <div class="buttons">
        <button class="add-button" @click="addMember">添加</button>
        <button class="cancle-button" @click="showAddMemberDialog = false">取消</button>
      </div>
    </div>
    <!-- 删除成员弹窗 -->
    <div v-if="showDeleteMemberDialog" class="deletebox">
      <div class="box-title">删除确认</div>
      <div class="divider"></div>
      <div class="confirm-text">{{ confirmText }}</div>
      <div class="buttons">
        <button class="confirm-button" @click="confirmDelete">确定</button>
        <button class="cancle-button" @click="showDeleteMemberDialog = false">取消</button>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'; // 新增useRoute
import { ElInput, ElCheckbox, ElIcon, ElMessage } from 'element-plus';
import { Search, HomeFilled, Setting, ChatDotRound, QuestionFilled, Briefcase, UserFilled, Comment } from '@element-plus/icons-vue';

// 获取路由实例和路由参数
const route = useRoute(); // 新增路由参数获取

const companyData = ref(null); // 初始化为null
const members = ref([]);
const isRoot = ref(false);

// 检查用户角色
const checkUserRole = () => {
  const userRole = localStorage.getItem('userRole');
  isRoot.value = userRole === 'ROOT';
};

const currentUsername = localStorage.getItem('username');

const isCurrentUser = (username) => {
  return username === currentUsername;
};

// 新增获取公司信息方法
const fetchCompanyInfo = async () => {
  try {
    const token = localStorage.getItem('token'); 
    console.log('token:', token);
    let apiUrl = 'http://113.44.170.52:8080/agent/get-company-info';
    
    // 从路由查询参数获取公司名称
    const companyName = route.query.companyName;
    if (companyName) {
      apiUrl += `?company-name=${encodeURIComponent(companyName)}`;
    }

    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `${token}`
      }
    });

    if (!response.ok) throw new Error('获取数据失败');
    
    const data = await response.json();
    console.log('从后端获取的原始数据:', data);
    // 添加数据有效性验证
    if (!data?.data?.Company || !Array.isArray(data.data.Members)) {
      throw new Error('返回数据格式错误');
    }
   // 处理返回数据
   companyData.value = {
      name: data.data.Company.name || '',
      member_num: data.data.Members.length,
      system_num: data.data.Company.system_num || 0
    };

    members.value = data.data.Members.map(member => ({
      ...member,
      isSelected: false // 保持原有的选择状态字段
    }));
    
  } catch (error) {
    ElMessage.error(error.message || '获取公司信息失败');
    console.error('API Error:', error);
  }
};
// 在组件挂载时自动获取数据
onMounted(() => {
  checkUserRole();
  fetchCompanyInfo();
});


const isAllSelected = ref(false);
const searchQuery = ref('');
const showAddMemberDialog = ref(false);
const showDeleteMemberDialog = ref(false);
const username = ref('');
const email = ref('');
const passwordType = ref('password');
const confirmText = ref('');
const selectedMembersToDelete = ref([]);

// 工具栏状态管理
const selectedTool = ref('home'); 
const currentView = ref('home'); 

// 获取路由实例
const router = useRouter();
// 处理工具栏点击事件
const handleToolClick = (tool) => {
  selectedTool.value = tool;
  switch (tool) {
    case 'home':
      router.push('/headbar/home');
      break;
    case 'systemadmin':
      router.push('/headbar/systemadmin');
      break;
  }
};
// 全选/取消全选逻辑
const handleSelectAll = () => {
  members.value.forEach(member => {
    member.isSelected = isAllSelected.value;
  });
};

// 检查是否全选
const checkAllSelected = () => {
  isAllSelected.value = members.value.every(member => member.isSelected);
};

// 打开删除单个成员确认弹窗
const openDeleteMemberDialog = (member) => {
  confirmText.value = `确定要删除 ${member.username} 吗？`; // 修正为username
  selectedMembersToDelete.value = [member];
  showDeleteMemberDialog.value = true;
};

// 打开删除选中成员确认弹窗
const openDeleteSelectedDialog = () => {
  const selectedMembers = members.value.filter(member => member.isSelected);
  if (selectedMembers.length === 0) {
    alert('请先选择要删除的成员');
    return;
  }
  confirmText.value = `确定要删除${selectedMembers.length}个成员吗？`;
  selectedMembersToDelete.value = selectedMembers;
  showDeleteMemberDialog.value = true;
};

// 确认删除成员（同时处理单个和批量）
const confirmDelete = async () => {
  try {
    const token = localStorage.getItem('token');
    const usernames = selectedMembersToDelete.value.map(m => m.username);
    
    const response = await fetch('http://113.44.170.52:8080/agent/deleteMembers', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `${token}`
      },
      body: JSON.stringify({ usernames })
    });

    const result = await response.json();

    if (!response.ok) {
      throw new Error(result.message || '删除成员失败');
    }

    ElMessage.success(result.message);
    
    // 仅保留接口刷新方式（重要修改！）
    await fetchCompanyInfo();

  } catch (error) {
    ElMessage.error(error.message);
    console.error('删除失败:', error);
  } finally {
    showDeleteMemberDialog.value = false;
    selectedMembersToDelete.value = [];
  }
};


// 打开添加成员弹窗
const openAddMemberDialog = () => {
  showAddMemberDialog.value = true;
};

const addMember = async () => {
  try {
    if (!username.value || !email.value) {
      ElMessage.warning('请输入成员姓名和邮箱');
      return;
    }

    const token = localStorage.getItem('token');
     const response = await fetch('http://113.44.170.52:8080/agent/addMember', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `${token}`
      },
      body: JSON.stringify({
        username: username.value,
        email: email.value
      })
    });

    const result = await response.json();

    if (!response.ok) {
      throw new Error(result.message || '添加成员失败');
    }

    ElMessage.success(result.message);
    // 添加成功后刷新成员列表
    await fetchCompanyInfo();
    showAddMemberDialog.value = false;
    username.value = '';
    email.value = '';
  } catch (error) {
    ElMessage.error(error.message);
    console.error('添加成员失败:', error);
  }
};

const togglePasswordVisibility = () => {
  passwordType.value = passwordType.value === 'password'? 'text' : 'password';
};

const handlePasswordInput = () => {
  // 处理密码输入逻辑
};

// 返回系统管理页面
const goBackToSystemAdmin = () => {
  router.push('/headbar/systemadmin');
};
</script>      


<style scoped>
@font-face {
  font-family: 'PangMenZhengDao';
  src: url('@/assets/PangMenZhengDaoBiaoTiTiMianFeiBan-2.ttf');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'Ubuntu';
  src: url('@/assets/._Ubuntu-M.ttf');
  font-weight: normal;
  font-style: normal;
}

.companyadmin {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 100vh;
  background-color: #000000;
}

.left {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: #000000;
}

.company-info {
  background-color: rgb(94, 118, 144, 0.34);
  border: 1px solid #374151;
  border-radius: 1rem;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 25px;
  margin: 23px 30px 15px 30px;
}

.company-info-content {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
}

.el-button.back-button {
  background-color: rgb(123, 136, 150, 0.73);
  width: 150px;
  height: 43px;
  color: white;
  font-size: 16px;
  border-radius: 12px;
}

.el-button.back-button:hover {
  background-color: rgba(87, 97, 106, 0.38);
  color: white;
}

.el-button.back-button:active {
  background-color: rgba(65, 72, 79, 0.38);
  color: white;
}

.el-button.forward-button {
  background-color: rgb(123, 136, 150, 0.39);
  width: 150px;
  height: 43px;
  color: white;
  font-size: 16px;
}

.el-button.forward-button:hover {
  background-color: rgba(87, 97, 106, 0.38);
  color: white;
}

.el-button.forward-button:active {
  background-color: rgba(65, 72, 79, 0.38);
  color: white;
}

.company-middle-info {
  text-align: center;
}

.company-name {
  color: white;
  font-size: 30px;
  font-weight: bold;
}

.count-info {
  color: white;
  font-size: 16px;
  display: flex;
  justify-content: center;
  gap: 100px;
}

.main-content {
  background-color: rgb(94, 118, 144, 0.34);
  border-radius: 1rem;
  padding: 25px;
  margin: 3px 30px 900px 30px;
  border: 1px solid #374151;
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
}

.el-button.button {
  background-color: rgb(123, 136, 150, 0.39);
  border: rgb(123, 136, 150, 0.39);
  width: 35px;
  height: 35px;
  color: white;
  font-size: 16px;
  color: white;
  font-size: 20px;
  border-radius: 7px;
}

.el-button.button:hover {
  background-color: rgba(87, 97, 106, 0.38);
  color: white;
}

.el-button.button:active {
  background-color: rgba(65, 72, 79, 0.38);
  color: white;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-bar {
  width: 50%;
  background-color: #1f2931;
  padding: 1rem 5rem;
  border-radius: 1rem;
  margin: 0 auto;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.toolbar {
  width: 5rem;
  padding: 1rem 0;
  background-color: #1f2931;
  display: flex;
  flex-direction: column;
  gap: 20px;
  border-left: 1px solid #374151;
}

.tool-item {
  text-align: center;
  cursor: pointer;
  color: #bbbbbb;
  transition: color 0.2s ease;
}

.tool-item:hover {
  color: #636161;
}

.active {
  color: #636161!important;
}

.member-list {
  width: 100%;
  height: 100%;
  margin-top: 12px;
  overflow-y: auto;
  color: white;
}

.member-list::-webkit-scrollbar {
  display: none;
}

.member-list {
  scrollbar-width: none;
}

.member-header {
  display: flex;
  font-size: 15px;
  font-weight: bold;
  color: white;
  margin-bottom: 7px;
  align-items: center;
}

.header-item {
  height: 45px;
  padding: 5px;
  margin-right: 10px;
  background-color: rgb(94, 118, 144, 0.34);
  border-radius: 7px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
}

.header-item:last-child {
  margin-right: 0;
}

.select-header {
  width: 100px;
  display: flex;
  justify-content: center;
}

.name-header {
  width: 250px;
}

.email-header {
  flex: 1;
}

.action-header {
  width: 150px;
  display: flex;
  justify-content: center;
}

.member-row {
  display: flex;
  margin-bottom: 7px;
  border-radius: 5px;
  height: 45px;
}

.member-item {
  padding: 10px;
  font-size: 15px;
  margin-right: 10px;
  /* 增大成员元素右边距 */
  border-radius: 7px;
  background-color: rgb(123, 136, 150, 0.38);
  display: flex;
  justify-content: center;
  align-items: center;
}

.member-item:last-child {
  margin-right: 0;
}

.select-item {
  width: 100px;
  display: flex;
  justify-content: center;
}

.name-item {
  width: 250px;
}

.email-item {
  flex: 1;
}

.deletebutton {
  width: 150px;
  display: flex;
  justify-content: center;
  border-radius: 7px;
  background-color: rgb(123, 136, 150, 0.38);
  color: white; 
  align-items: center; /* 添加这一行，使文字在垂直方向居中 */
  height: 45px; /* 添加合适的高度，让布局更稳定 */
}

.deletebutton:hover {
  background-color: rgba(87, 97, 106, 0.38);
}

.deletebutton:active {
  background-color: rgba(65, 72, 79, 0.38);
}

.add-member-dialog.el-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  width: 60vw;
  max-width: 660px;
  height: 60vh;
  background-color: #333333;
  color: white;
  padding: 20px;
  border-radius: 10px;
}

/* 添加成员弹窗 */
.addbox {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60vw;
  max-width: 660px;
  height: 41vh;
  background-color: #222222;
  border: 1px solid #636161;
  color: white;
  padding: 10px;
  border-radius: 10px;
}

.box-title {
  text-align: left;
  margin-left: 10px;
  margin-top: 0%;
  font-size: 20px;
  font-weight: bold;
}

.divider {
  width: 96%;
  height: 1px;
  background-color: #636161;
  margin: 10px auto;
}

.input-title{
  text-align: left;
  margin-left: 30px;
  color:#9A9A9A;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 0px;
}

.bar,
.bar2 {
  background-color: rgb(94, 118, 144, 0.34);
  border: 1px solid #636161;
  color: #9A9A9A;
  font-size: 16px;
  box-sizing: border-box;
  border-radius: 15px;
  height: 6vh;
  width: 80%;
  z-index: 2;
  padding-left: 60px;
}

.bar {
  margin: 0.5vh 0 2vh 0;
}

.bar2 {
  margin: 0.5vh 0 0 0;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.input-icon1,
.input-icon2 {
  position: absolute;
  left: 12%;
  transform: translateY(-50%);
  color: white;
  font-weight: bold;
  font-size: 38px;
  z-index: 4;
}

.input-icon1 {
  top: 50%;
}

.input-icon2 {
  top: 66%;
}
 .buttons{
  display: flex;
  justify-content: center;
  gap:20px;

 }

.add-button {
  width: 35%;
  height: 6vh;
  background-color: rgb(39,67,124,70);
  font-size: 20px;
  font-weight: bold;
  color: white;
  margin-bottom: 2vh;
  z-index: 2;
  margin-top: 3vh;
  margin-bottom: 3.4vh;
  border-radius: 15px;
  border: none;
}

.add-button:hover {
  background-color: #21396a;
  color: white;
}

.add-button:active {
  background-color: rgb(25, 49, 74);
  color: white;
}

.cancle-button {
  width: 35%;
  height: 6vh;
  background-color: #636161;
  font-size: 20px;
  font-weight: bold;
  color: white;
  margin-bottom: 2vh;
  z-index: 2;
  margin-top: 3vh;
  margin-bottom: 3.4vh;
  border-radius: 15px;
  border: none;
}

.cancle-button:hover {
  background-color: #504f4f;
  color: white;
}

.cancle-button:active {
  background-color: #484848;
  color: white;
}

.deletebox {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60vw;
  max-width: 660px;
  height: 25vh;
  background-color: #222222;
  border: 1px solid #636161;
  color: white;
  padding: 10px;
  border-radius: 10px;
}

.confirm-text{
  margin-top: 3vh;
  font-size: 18px;
}
.confirm-button {
  width: 35%;
  height: 6vh;
  background-color: rgb(39,67,124,70);
  font-size: 20px;
  font-weight: bold;
  color: white;
  margin-bottom: 2vh;
  z-index: 2;
  margin-top: 3vh;
  margin-bottom: 3.4vh;
  border-radius: 15px;
  border: none;
}

.confirm-button:hover {
  background-color: #21396a;
  color: white;
}

.confirm-button:active {
  background-color: rgb(25, 49, 74);
  color: white;
}

.company-admin {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
  margin-top: 20px; /* 增加与顶栏的间距 */
}

.content-container {
  max-width: 1400px; /* 增加最大宽度 */
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}
</style>

